package com.eqdd.yiqidian.ui.companyspace

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.ProductDemandBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimImageSelectBean
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.ui.SingleChooseActivity
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity
import com.eqdd.yiqidian.utils.HttpUtil
import com.eqdd.yiqidian.utils.ImageUtil
import com.eqdd.yiqidian.utils.PicUtil
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_recyclerview.*
import kotlinx.android.synthetic.main.list_item_23.*
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast


/**
 *
 * Created by jhj on 18-7-21.
 */
class ProductIndexAddActivity : SlimBaseMultiEditActivity() {

    val indexBean = ProductDemandBean.IndexListBean()

    override fun initBinding() {
        clearData()
        setContentView(R.layout.activity_recyclerview)
        initTopTitleBar(View.VISIBLE, "指标")

        val type = intent.getIntExtra(Config.TYPE, -1)
        var url = ""
        if (type == 0) {
            url = HttpConfig.BASE_URL + HttpConfig.SUPPLY_INDEX_ADD
        } else if (type == 1) {
            url = HttpConfig.BASE_URL + HttpConfig.BUYER_INDEX_ADD
        } else {
            return
        }

        initTopRightText("新增", View.OnClickListener {
            if (!checkParams()) {
                toast(msg ?: "")
                return@OnClickListener
            }

            OkGo.post<HttpResult<*>>(url)
                    .params("userGuid", user.guid)
                    .params("companyId", user.companyId)
                    .params(uploadParams())
                    .execute(object : DialogCallBack<HttpResult<*>>(this) {
                        override fun onSuccess(response: Response<HttpResult<*>>) {
                            val httpResult = response.body()
                            if (httpResult?.status == 200) {
                                toast(msg ?: "上传成功")
                                val intent = Intent()
                                intent.putExtra("data", indexBean)
                                setResult(Activity.RESULT_OK, intent)
                                finish()
                            } else {
                                toast("上传失败")
                            }
                        }
                    })
        })
    }

    override fun initRecyclerView(): RecyclerView {
        return recyclerView
    }


    fun uploadParams(): HttpParams {
        val bean = slimAdapterEx.data
        val params = HttpParams()
        params.put("productId", intent.getIntExtra(Config.ID, -1))
        params.put("productBuyerId", intent.getIntExtra(Config.ID, -1))
        params.put("indexTypeKey", bean[0].content)
        params.put("indexTypeValue", bean[1].content)
        (bean[2].tag as String?)?.let {
            val str = if (it.startsWith("http")) {
                val index = it.indexOf("/", 10, true)
                it.substring(index, it.length)
            } else {
                it
            }
            params.put("indexImage", str)
        }
        indexBean.indexTypeKey = bean[0].content
        indexBean.indexTypeValue = bean[1].content
        indexBean.indexImage = bean[2].tag as String? ?: ""
        return params
    }

    override fun setEditBeans() {
        datas.add(SlimEditEnterBean("指     标", "", 0, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("指 标 值", "", 1, "请输入").setNeed(true))
        datas.add(SlimImageSelectBean("指标图片", 2, ""))
        slimAdapterEx.register(R.layout.layout_image_selected, SlimInjector<com.eqdd.yiqidian.bean.rebuild.slimedit.SlimImageSelectBean> { data, injector ->
            injector?.text(R.id.tv_label, data?.title)
                    ?.clicked(R.id.iv_add) {
                        PicUtil.single(this@ProductIndexAddActivity, true)
                    }
        })
    }

    override fun itemClick(p: Int) {
        when (p) {
            0 -> startActivityForResult<SingleChooseActivity>(Config.ADD, Config.TYPE to 49, Config.TITLE to "指标")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && requestCode == Config.ADD) {
            val str = data?.getStringExtra("data")
            slimAdapterEx.getDataItem(0).content = str
            slimAdapterEx.notifyItemChanged(0)
        }
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            val localMedias = PictureSelector.obtainMultipleResult(data)
            ImageUtil.setImage(localMedias?.get(0)?.compressPath, iv_add)
            HttpUtil.upLoadPic(this@ProductIndexAddActivity, localMedias[0].compressPath) { url ->
                slimAdapterEx.getDataItem(2).tag = url
            }

        }
    }
}